package org.urchr.beorganized.api.impl.user;

import org.postgresql.util.Base64;
import org.urchr.beorganized.api.base.BaseAPIServlet;
import org.urchr.beorganized.dao.UsersDAO;
import org.urchr.beorganized.dao.XMLDocumentBuilder;
import org.urchr.beorganized.dao.errors.DBErrorException;
import org.urchr.beorganized.dao.errors.GeneralException;
import org.urchr.beorganized.dao.tables.User;

public class RegisterUser extends BaseAPIServlet {

	@Override
	protected void doProcess() throws GeneralException {
		if(xmlObject!=null){
//			System.out.println("xmlObject: name = "+
//					xmlObject.getNodeName()+", login: "+xmlObject.getAttribute("login"));
			User user = UsersDAO.registerUser(xmlObject);
			XMLDocumentBuilder doc = new XMLDocumentBuilder();
			UsersDAO.userToNode(doc, doc.getRootElement("user"), user);
			String string = user.getLogin()+"@"+user.getPassword();
			doc.getRootElement().setAttribute("token", Base64.encodeBytes(string.getBytes()));
			sendNode(doc.getRootElement());			
		}else{
//			System.out.println("xmlObject is null");
			throw new DBErrorException();
		}
	}

}
